package com.dcy.system.dao;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dcy.common.base.dao.DcyBaseDao;
import com.dcy.common.constant.SqlConstant;
import com.dcy.common.enums.BaseModelDelFlagEnum;
import com.dcy.common.model.BaseModel;
import com.dcy.common.model.PageModel;
import com.dcy.system.mapper.UserInfoMapper;
import com.dcy.system.model.UserInfo;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dcy
 * @since 2022-11-08
 */
@Service
public class UserInfoDao extends DcyBaseDao<UserInfoMapper, UserInfo> {

    /**
     * 获取表格数据
     *
     * @param userInfo
     * @param pageModel
     * @return
     */
    public IPage<UserInfo> pageListByEntity(UserInfo userInfo, PageModel pageModel) {
        QueryWrapper<UserInfo> queryWrapper = Wrappers.<UserInfo>query();
        queryWrapper.eq("userInfo." + BaseModel.DEL_FLAG, BaseModelDelFlagEnum.NORMAL.getCode());
        queryWrapper.like(StrUtil.isNotBlank(userInfo.getUsername()), "userInfo." + UserInfo.USERNAME, userInfo.getUsername());
        queryWrapper.and(StrUtil.isNotBlank(userInfo.getDeptId()), userInfoQueryWrapper -> {
                    userInfoQueryWrapper.eq("userInfo." + UserInfo.DEPT_ID, userInfo.getDeptId())
                            .or().inSql("userInfo." + UserInfo.DEPT_ID, "SELECT sys_dept.id FROM sys_dept WHERE FIND_IN_SET('" + userInfo.getDeptId() + "', ancestors)");
                }
        );
        return baseMapper.selectPageList(getPagePlusInfo(pageModel), queryWrapper);
    }

    public IPage<UserInfo> pageListByEntityLam(UserInfo userInfo, PageModel pageModel) {
        final LambdaQueryWrapper<UserInfo> queryWrapper = Wrappers.<UserInfo>lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(userInfo.getUsername()), UserInfo::getUsername, userInfo.getUsername());
        return pageList(pageModel, queryWrapper);
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    public UserInfo getUserInfoByUsername(String username) {
        return getOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUsername, username).last(SqlConstant.DEFAULT_ONE_LAST_SQL));
    }
}
